package br.com.kariri.smartschool.ui.util.window {
	
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	
	import mx.containers.Box;
	import mx.containers.Canvas;
	import mx.containers.ControlBar;
	import mx.containers.TabNavigator;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.DateField;
	import mx.controls.Image;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.core.Container;
	import mx.core.UIComponent;
	import mx.effects.Blur;
	import mx.effects.Fade;
	import mx.effects.Move;
	import mx.effects.Parallel;
	import mx.effects.Resize;
	import mx.effects.Sequence;
	import mx.effects.Zoom;
	import mx.events.EffectEvent;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	
	
	[Event(name="minimize", type="br.com.kariri.smartschool.ui.util.window.WindowPanelEvent")]
	[Event(name="maximize", type="br.com.kariri.smartschool.ui.util.window.WindowPanelEvent")]
	[Event(name="close", type="br.com.kariri.smartschool.ui.util.window.WindowPanelEvent")]
	/**
	 * @author Fabiel Prestes
	 */
	public class WindowPanel extends BaseCustomPanel {
		
		private var imgClose:Image;
		private var imgMaximize:Image;
		private var imgMinimize:Image;
		
		[Embed(source="br/com/kariri/smartschool/ui/icons/window.png")]
		[Bindable]
		private var imgTitleWindow:Class;
		
		private var glow:GlowFilter;
		
		private var sequenceMinimizar:Sequence;
		
		private var parallelMaximizar:Parallel;
		private var moveMaximizar:Move;
		private var resizeMaximizar:Resize;
		
		private var parallelMinimizar:Parallel;
		private var resizeMinimizar:Resize;
		private var moveMinimizar:Move;
		
		private var widthOriginal:Number;
		private var heightOriginal:Number;
		
		[Bindable]
		private var xOriginal:Number;
		
		[Bindable]
		private var yOriginal:Number;
		
		public var panelRoot:UIComponent;
		public var bar:Box;
		
		
		/**
		 * Contrutor Padrão
		 */
		public function WindowPanel() {
			super();
		}
		
		/**
		 * @inheritDoc
		 */
		override protected function childrenCreated():void{
			this.setStyle("styleName", "windowpanel");
			
			configButtons();
			
			super.childrenCreated();
			
			widthOriginal = this.width as Number;
			heightOriginal = this.height as Number;

			configButtonsEffect();
			
		}
		
		/**
		 * @private
		 * Metodo responsavel por guarda a posição X e Y atual da tela para que
		 * assim ao maximizar a tela a mesma volte para a sua posição original.
		 */
		private function trateMouseUpMinimizar(evt:MouseEvent):void{
			xOriginal = this.x;
			yOriginal = this.y;
		}
		
		/**
		 * @private
		 * Responsavel por criar e configurar os botoes de Maximizar, Minimizar e Fechar.
		 */
		private function configButtons():void{
			
			imgMaximize = new Image();
			imgMaximize.source = "assets/img/maximizar.png";
			imgMaximize.width = 20;
			imgMaximize.height = 20;
			
			imgMinimize = new Image();
			imgMinimize.source = "assets/img/minimizar.png";
			imgMinimize.width = 20;
			imgMinimize.height = 20;
			
			imgClose = new Image();
			imgClose.source = "br/com/kariri/smartschool/ui/icons/buttons/close.png";
			imgClose.width = 16;
			imgClose.height = 16;
			
			
			this.titleIcon = imgTitleWindow;
			
			
			imgMaximize.addEventListener(MouseEvent.MOUSE_OVER, trateMouseOver);
			imgMaximize.addEventListener(MouseEvent.MOUSE_OUT, trateMouseOut);
			imgMaximize.addEventListener(MouseEvent.CLICK, trateMaximizarClick);
			
			imgMinimize.addEventListener(MouseEvent.MOUSE_OVER, trateMouseOver);
			imgMinimize.addEventListener(MouseEvent.MOUSE_OUT, trateMouseOut);
			imgMinimize.addEventListener(MouseEvent.CLICK, trateMinimizarClick);
			imgMinimize.addEventListener(MouseEvent.MOUSE_UP, trateMouseUpMinimizar);
			
			imgClose.addEventListener(MouseEvent.MOUSE_OVER, trateMouseOver);
			imgClose.addEventListener(MouseEvent.MOUSE_OUT, trateMouseOut);
			imgClose.addEventListener(MouseEvent.CLICK, trateFecharClick);
			
			this.arrayFilhos.push(imgClose);
			//this.arrayFilhos.push(imgMaximize);
			//this.arrayFilhos.push(imgMinimize);
		}
		
		/**
		 * @private
		 * Responsavel por instanciar e configurar os efeitos que serão realizados
		 * pelo click do mouse nas imagens no HEADER.
		 */
		private function configButtonsEffect():void{
			/* Este efeito será utilizado quando o mouse estiver em cima do botoes/imagens
			 * no HEADER */
			glow = new GlowFilter();
            glow.color = 0xffffff;
            glow.blurX = glow.blurY = 20;
		}
		
		/**
		 * @private
		 * Responsavel por instanciar e configurar os efeitos que serão realizados
		 * pelo click do mouse na imagem de Maximizar.
		 */
		private function configEfeitoMaximizar():void{
            
            if(moveMaximizar == null){
            	moveMaximizar = new Move(this);
	            moveMaximizar.duration = 600;
            }
			
			moveMaximizar.xFrom = bar.x;
			moveMaximizar.yFrom = bar.y;
			
            moveMaximizar.xTo = xOriginal;
            moveMaximizar.yTo = yOriginal;
            
            if(resizeMaximizar == null){
	            
				resizeMaximizar = new Resize(this);
	            
	            resizeMaximizar.heightTo = heightOriginal;
	            resizeMaximizar.widthTo = widthOriginal;
	            resizeMaximizar.duration = 600;
				
            }
            
			if(parallelMaximizar == null){
				
				parallelMaximizar = new Parallel(this);
				
	            parallelMaximizar.addChild(moveMaximizar);
	            parallelMaximizar.addChild(resizeMaximizar);
				
   			}
		}
		
		/**
		 * @private
		 * Responsavel por instanciar e configurar os efeitos que serão realizados
		 * pelo click do mouse na imagem de Minimizar.
		 */
		private function configEfeitoMinimizar():void{
			if(resizeMinimizar == null){
	            resizeMinimizar = new Resize(this);
	            resizeMinimizar.widthTo = 200;
	            resizeMinimizar.heightTo = 35;
	            resizeMinimizar.duration = 600;
			}
			
			if(moveMinimizar == null){
	            moveMinimizar = new Move(this);
	            moveMinimizar.duration = 600;
				
			}
			
			var filhosBarra:int = bar.getChildren().length;
						
			if(filhosBarra >= 1){
				moveMinimizar.xTo = (bar.getChildAt(0).width + 10) * filhosBarra;
			}else{
	            moveMinimizar.xTo = bar.x;
			}

            moveMinimizar.yTo = bar.y; 
            
            if(parallelMinimizar == null){
	            parallelMinimizar = new Parallel();
            	parallelMinimizar.addChild(resizeMinimizar);
	            parallelMinimizar.addChild(new Blur());
	            parallelMinimizar.addChild(moveMinimizar);
            }
			
			if(sequenceMinimizar == null){
	            sequenceMinimizar = new Sequence(this);
				sequenceMinimizar.addChild(parallelMinimizar);
	            sequenceMinimizar.addEventListener(EffectEvent.EFFECT_END, trateFimEfeitoMinimizar);
			}
		}
		
		/**
		 * @private
		 * Trata o OVER do mouse nas imagens do HEADER
		 */
		private function trateMouseOver(evt:MouseEvent):void{
            evt.currentTarget.filters = [glow];
		}
		
		/**
		 * @private
		 * Trata o OUT do mouse nas imagens do HEADER
		 */
		private function trateMouseOut(evt:MouseEvent):void{
			evt.currentTarget.filters = [];
		}
		
		/**
		 * @private
		 * Trata o CLICK da imagem maximizar do HEADER
		 */
		private function trateMaximizarClick(evt:MouseEvent):void{
			
			bar.removeChild(this);
			
			PopUpManager.addPopUp(this, panelRoot);
			
			configEfeitoMaximizar();
			parallelMaximizar.play();
			this.dispatchEvent(new WindowPanelEvent(WindowPanelEvent.MAXIMIZE));
			this.width = widthOriginal;
			this.height = heightOriginal;
			
		}
		
		/**
		 * @private
		 * Trata o CLICK da imagem minimizar do HEADER
		 */
		private function trateMinimizarClick(evt:MouseEvent):void{
			
			try{
				configEfeitoMinimizar();
			}catch(er:Error){
			
			}
			
			sequenceMinimizar.play();	
			
		}
		
		/**
		 * @private
		 * Trata o CLICK da imagem fechar do HEADER
		 */
		private function trateFecharClick(evt:MouseEvent):void{
			
			var blur:Fade = new Fade(this);
			blur.duration = 600;
			blur.addEventListener(EffectEvent.EFFECT_END, trateFimEfeitoFechar);
			blur.alphaTo = 0.0;
			blur.play();
		}
		
		/**
		 * @private
		 * Apos terminar o efeito de minimizar, é dispachado o evento do tipo MINIMIZAR
		 */
		private function trateFimEfeitoMinimizar(evt:EffectEvent):void{
			bar.addChild(this);
			this.dispatchEvent(new WindowPanelEvent(WindowPanelEvent.MINIMIZE));
		}
		
		
		/**
		 * Utilizado para limpar os proprios campos do panel  
		 * 
		 */
		public function clear():void
		{
			
			var components : Array = this.getChildren();
			var yet:Boolean = false;
			for (var i:int =0 ; i<components.length; i++){
				
				if (components[i] is TextInput){
					if(!yet){
						(components[i] as TextInput).setFocus();
						yet = true; 
					}
					(components[i] as TextInput).text="";
				}else if (components[i] is Button){
					//(components[i] as Button).selected = false;
				}else if (components[i] is DateField){
					(components[i] as DateField).selectedDate = null;
				}
			}
			
		}
		
		/**
		 * Utilizado para limpar os campos de um canvas 
		 * 
		 */
		public static function clearCanvasChildren(canvas:Container):void
		{
			var components : Array = canvas.getChildren();
			var yet:Boolean = false;
			for (var i:int =0 ; i<components.length; i++){
				
				if (components[i] is TextInput){
//					if(!yet){
//						(components[i] as TextInput).setFocus();
//						yet = true; 
//					}
					(components[i] as TextInput).text="";
				}else if (components[i] is Button){
					//(components[i] as Button).selected = false;
				}else if (components[i] is DateField){
					(components[i] as DateField).text = "";
					(components[i] as DateField).selectedDate = null;
				}else if (components[i] is TextArea){
					(components[i] as TextArea).text = "";
					
				}else if(components[i] is Container){
					clearCanvasChildren(components[i]);
				}
			}
			
		}
		
		/**
		 * @private
		 * Apos terminar o efeito de mafechar, é dispachado o evento do tipo FEHCAR
		 * e logo em seguida a tela é removida.
		 */
		private function trateFimEfeitoFechar(evt:EffectEvent):void{
			try{
				PopUpManager.removePopUp(this);
				bar.removeChild(this);
				panelRoot.removeChild(this);
			}catch(er:Error){}
			this.dispatchEvent(new WindowPanelEvent(WindowPanelEvent.FECHAR));
		}
	}
}